import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userInfo: {
			address:'',
			age:'',
			avatarImg:'',
			balance:'',
			certification:'',
			claimExpression:'',
			connectQq:'',
			connectSina:'',
			connectWeixin:'',
			createIpAddress:'',
			createTime:'',
			description:'',
			education:'',
			email:'',
			favouriteSubject:'',
			gender:'',
			id:'',
			loginMode:'',
			memberId:'',
			nickName:'',
			password:'',
			payment:'',
			professional:'',
			realName:'',
			signature:'',
			status:'',
			telephone:'',
			type:'',
			username:'',
			workUnitCurrent:'',
			workUnitFormer:''
		},
		hasLogin: false,
		loginProvider: "",
		openid: null,
		databaseInfo: {}, //资源库全局变量
		propertyInfo:{} ,//资源库-属性全局变量
		topic: {},//话题
	},
	mutations: {
		login(state, userInfo) {
			state.hasLogin = true;
			state.userInfo = userInfo;
		},
		logout(state) {
			state.hasLogin = false;
			state.openid = null;
			state.userInfo = {
				address:'',
				age:'',
				avatarImg:'',
				balance:'',
				certification:'',
				claimExpression:'',
				connectQq:'',
				connectSina:'',
				connectWeixin:'',
				createIpAddress:'',
				createTime:'',
				description:'',
				education:'',
				email:'',
				favouriteSubject:'',
				gender:'',
				id:'',
				loginMode:'',
				memberId:'',
				nickName:'',
				password:'',
				payment:'',
				professional:'',
				realName:'',
				signature:'',
				status:'',
				telephone:'',
				type:'',
				username:'',
				workUnitCurrent:'',
				workUnitFormer:'',
			};
		},
		setOpenid(state, openid) {
			state.openid = openid;
		},
		setProvider(state, provider) {
			state.loginProvider = provider;
		},
		setDatabaseInfo(state, databaseInfo) {
			state.databaseInfo = databaseInfo;
		},
		setPropertyInfo(state, propertyInfo) {
			state.propertyInfo = propertyInfo;
		},
		setTopic(state, topic) {
			state.topic = topic;
		}
	},
	actions: {
		// lazy loading openid 
		getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function () { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		}
	}
})

export default store
